package com.ja.openchat.viewmodels;

import static com.blankj.utilcode.util.StringUtils.getString;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.util.Log;
import android.util.Pair;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.ja.openchat.BuildConfig;
import com.ja.openchat.ui.login.LoginActivity;
import com.zy.openchat.core.manager.AuthUserInfo;
import com.zy.openchat.core.manager.AuthUserManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.ja.openchat.ui.MainActivity;
import com.zy.openchat.Constants;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.ConfirmPopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.utils.KLog;


public class SplashViewModel extends BaseViewModel {

    private ConfirmPopupView mConfirmPopupView;
    private boolean isPopuWaring = false;
    private int startRetryIndex = 0;
    private final int MAX_RETRY_INDEX = BuildConfig.ServerHosts.length-1;
    private Intent intent;
    private Activity activty;

    public SplashViewModel(@NonNull Application application, BaseModel model) {
        super(application, model);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        KLog.i("splashviewModel  tg_event =====  "+tg_event.event);

        switch (tg_event.event) {
            case EUser_To_TdConfig:
                configTd();
                break;
            case EUser_To_Check_Encryption:
                check();
                break;
            case EUser_Td_Connection_State_Changed:
                checkToJump();
                break;
            case EUser_Td_Input_Phone:
            case EUser_Td_Input_Code:
            case EUser_Td_Register:
                isToJumpToLogin = true;
                checkToJump();
                break;
            default:
                break;
        }
    }

    private boolean isToJumpToLogin = false;
    private boolean isJump = false;
    public boolean isPricayOk = false;
    public void checkToJump(){
        if(isJump){
            return;
        }
        if(!isPricayOk){
            return;
        }
        if(TelegramManager.getTelegramManager().getTgData().getUserConnectionState()!= TelegramManager.GoUserConnectionState.GoUserConnectionState_Connecting){
            isJump = true;
            if(isToJumpToLogin){
                startActivity(LoginActivity.class);
            }else{
                if(activty.getIntent()!=null){
                    MainActivity.start(activty,activty.getIntent().getAction(),activty.getIntent().getExtras(),activty.getIntent().getData());
                }else{
                    MainActivity.start(activty);
                }
            }
            finish();
        }
    }

    public void configTd() {
        Log.d("startsplash","configTd");
        startRetryIndex = TelegramManager.getTelegramManager().startIndex;
        int length = BuildConfig.ServerHosts.length;
        if(startRetryIndex>=length){
            startRetryIndex = length-1;
            TelegramManager.getTelegramManager().startIndex = startRetryIndex;
            SPUtils.getInstance().put(TelegramManager.SPU_START_INDEX,startRetryIndex);
        }
        Observable.create(new ObservableOnSubscribe<Pair<Boolean,Integer>>() {

                    @Override
                    public void subscribe(@NotNull ObservableEmitter<Pair<Boolean,Integer>> emitter) throws Exception {
                        String[] serverHosts = BuildConfig.ServerHosts;
                        if(serverHosts!=null&&serverHosts.length>0){
                            int index = -1;
                            boolean isValid = false;
                            for(int i = startRetryIndex;i<serverHosts.length;i++){
                                String server = serverHosts[i];
                                boolean isDoaminValid = isAnalyseDomain(server);
                                if(index<0&&isDoaminValid){
                                    index = i;
                                }
                                isValid = isValid||isDoaminValid;
                                if(isDoaminValid){
                                    break;
                                }
                            }
                            if(index<0){
                                index = startRetryIndex;
                            }
                            emitter.onNext(new Pair<>(isValid,index));
                        }else{
                            emitter.onNext(new Pair<>(true,0));
                        }
                    }
                }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Pair<Boolean,Integer>>() {
                    @Override
                    public void accept(Pair<Boolean,Integer> result) throws Exception {
                        if(result.first){
                            toConfigTd(result.second);
                        }else{
                            if(isPopuWaring){
                                return;
                            }
                            isPopuWaring = true;
                            mConfirmPopupView = new XPopup.Builder(activty).autoDismiss(false).asConfirm("提示", "暂时无法连接到服务器，请稍后重试", "关闭", "重试", new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    isPopuWaring = false;
                                    if(mConfirmPopupView!=null){
                                        mConfirmPopupView.dismiss();
                                    }
                                    startRetryIndex++;
                                    if(startRetryIndex>MAX_RETRY_INDEX){
                                        startRetryIndex = 0;
                                    }
                                    configTd();
                                }
                            }, new OnCancelListener() {
                                @Override
                                public void onCancel() {
                                    finish();
                                }
                            }, false);
                            mConfirmPopupView.show();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        toConfigTd(0);
                    }
                });

    }

    private void toConfigTd(int index){
        String data_directory;
        AuthUserInfo curUser = AuthUserManager.getAuthUserManager().currentAuthUser();
        if (curUser != null) {
            Constants.Loge("AuthUserManager", new Gson().toJson(curUser));
            data_directory = curUser.data_directory;
        } else {
            data_directory = AuthUserManager.create_data_directory();
        }
        TelegramManager.getTelegramManager().setTdlibParameters(activty, data_directory, index,new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {

            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }
    private boolean isAnalyseDomain(String host){
        String IPAddress = "";
        InetAddress ReturnStr = null;
        try {
            ReturnStr = InetAddress.getByName(host);
            IPAddress = ReturnStr.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    private void check() {
        TelegramManager.getTelegramManager().checkDatabaseEncryptionKey(activty, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                KLog.i("response ===  "+response);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void setIntent(Intent intent) {
        this.intent = intent;
    }

    public void setActivty(Activity activty) {
        this.activty = activty;
    }
}
